import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', () => {
  // 状态
  const userInfo = ref(null)
  const token = ref('')
  const permissions = ref([])
  const roles = ref([])

  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const hasRole = computed(() => (role) => roles.value.includes(role))
  const hasPermission = computed(() => (permission) => permissions.value.includes(permission))

  // 方法
  const setUserInfo = (info) => {
    userInfo.value = info
  }

  const setToken = (newToken) => {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }

  const setPermissions = (newPermissions) => {
    permissions.value = newPermissions
  }

  const setRoles = (newRoles) => {
    roles.value = newRoles
  }

  const login = async (credentials) => {
    try {
      // 这里调用API登录
      // const response = await authApi.login(credentials)
      // setToken(response.token)
      // setUserInfo(response.user)
      // setPermissions(response.permissions)
      // setRoles(response.roles)
      
      // 模拟登录
      setToken('mock-token-123')
      setUserInfo({
        id: 1,
        username: 'admin',
        email: 'admin@example.com',
        avatar: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=100&h=100&fit=crop&crop=face'
      })
      setPermissions(['user:read', 'user:write', 'role:read', 'role:write'])
      setRoles(['admin'])
      
      return { success: true }
    } catch (error) {
      return { success: false, message: error.message }
    }
  }

  const logout = () => {
    userInfo.value = null
    token.value = ''
    permissions.value = []
    roles.value = []
    localStorage.removeItem('token')
  }

  const initFromStorage = () => {
    const savedToken = localStorage.getItem('token')
    if (savedToken) {
      token.value = savedToken
      // 这里可以根据token获取用户信息
    }
  }

  return {
    // 状态
    userInfo,
    token,
    permissions,
    roles,
    
    // 计算属性
    isLoggedIn,
    hasRole,
    hasPermission,
    
    // 方法
    setUserInfo,
    setToken,
    setPermissions,
    setRoles,
    login,
    logout,
    initFromStorage
  }
})
